import Vue from 'vue'
import Vuex, { Store } from 'vuex'
import storage from '../utils/storage'
Vue.use(Vuex)

export default new Store({
  state: {
    cart: storage.getItem('cart')
  },
  mutations: {
    addCart(state, payload) {
      let flag = false
      state.cart.forEach(item => {
        // 如果id一致表明已经存在商品这个时候只需要做数量上的修改
        if (item.id === payload.goodsinfo.id) {
          item.count += payload.goodsinfo.count
          flag = true
        }
      })
      if (!flag) {
        state.cart.push(payload.goodsinfo)
      }
      storage.setItem('cart', state.cart)
    }
  },
  getters: {
    // 计算商品总数量
    getAllCount(state) {
      let c = 0
      state.cart.forEach(item => {
        c += item.count
      })
      return c
    },
    getAllPrice(state) {
      let p = 0
      state.cart.forEach(item => {
        if (item.selected === true) {
          p += item.count * item.sell_price
        }
      })
      return p
    }
  }
})
